﻿using Framework.Common;
namespace Bright.NetCore.Api.Helpers
{
    /// <summary>
    /// 请求头操作帮助
    /// </summary>
    public static class HeaderHelpers
    {
        /// <summary>
        /// 获取指定请求头的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="context"></param>
        /// <param name="headerName"></param>
        /// <returns></returns>
        public static T GetHeaderValue<T>(HttpContext context, string headerName)
        {
            var head = GetHeaderValue(context, headerName);
            return head.ConvertToObject<T>();
        }

        /// <summary>
        /// 获取指定请求头的值
        /// </summary>
        /// <param name="context"></param>
        /// <param name="headerName"></param>
        /// <returns></returns>
        public static string GetHeaderValue(HttpContext context, string headerName)
        {
            if (context.Request.Headers.TryGetValue(headerName, out var values))
            {
                return values.ToString();
            }
            return null;
        }

        /// <summary>
        /// 获取所有请求头
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetAllHeaders(HttpContext context)
        {
            var headers = new Dictionary<string, string>();
            foreach (var header in context.Request.Headers)
            {
                headers[header.Key] = header.Value.ToString();
            }
            return headers;
        }

        /// <summary>
        /// 添加请求头
        /// </summary>
        /// <param name="context"></param>
        /// <param name="headerName"></param>
        /// <param name="headerValue"></param>
        public static void AddHeader(HttpContext context, string headerName, string headerValue)
        {
            context.Request.Headers.Append(headerName, headerValue);
        }

        /// <summary>
        /// 移除指定请求头
        /// </summary>
        /// <param name="context"></param>
        /// <param name="headerName"></param>
        public static void RemoveHeader(HttpContext context, string headerName)
        {
            context.Request.Headers.Remove(headerName);
        }
    }
}
